package com.onlyphoto.onlymall.mvp.view.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import androidx.core.content.ContextCompat
import com.onlyphoto.onlymall.R
import com.onlyphoto.onlymall.base.BaseActivity
import com.onlyphoto.onlymall.bean.request.AddressAddBean
import com.onlyphoto.onlymall.bean.request.DeleteAddressBean
import com.onlyphoto.onlymall.bean.response.AddressBean
import com.onlyphoto.onlymall.bean.response.RegionBean2
import com.onlyphoto.onlymall.listeners.NoDoubleClickListener
import com.onlyphoto.onlymall.mvp.contract.CEditAddress
import com.onlyphoto.onlymall.mvp.presenter.PEditAddressImpl
import com.onlyphoto.onlymall.utils.ToastUtil
import com.onlyphoto.onlymall.widget.AreaPickerView
import kotlinx.android.synthetic.main.activity_editaddress.*
import java.lang.StringBuilder


class EditAddressActivity : BaseActivity<PEditAddressImpl>(), CEditAddress.IVEditAddress, View.OnClickListener {

    var pickerView: AreaPickerView? = null
    var addressAddBean = AddressAddBean()
    var bean: AddressBean? = null
    var deleteBean: DeleteAddressBean? = null
    var isOrderConfirm: Boolean? = false

    override fun retry() {}

    override fun loadData() {
        //加载数据
    }

    @SuppressLint("SetTextI18n")
    override fun init() {
        bean = intent.getSerializableExtra("addressBean") as AddressBean?
        isOrderConfirm = intent.getBooleanExtra("isOrderConfirm", false)
        if (bean != null) {
            edt_name.setText(bean?.name)
            edt_name.setSelection(bean?.name!!.length)
            edt_phone.setText(bean?.phone)
            edt_street.setText(bean?.place)
            area_choose.text = bean?.province + "-" + bean?.city + "-" + bean?.district
            if (bean?.state == 1) {
                is_default?.setImageDrawable(ContextCompat.getDrawable(this, R.mipmap.btn_open))
                addressAddBean.default_set = 1
            }
            tv_title.text = "编辑收货地址"
            save.text = "保\u3000存"
            delete.visibility = View.VISIBLE
            save.isEnabled = true
            addressAddBean.address_id = bean?.id!!
            deleteBean = DeleteAddressBean(bean?.id!!)
        }
        if (isOrderConfirm!!) {
            save.text = "保存并使用"
        }
    }

    override fun getRegionSuccess(bean: RegionBean2) {
        if (pickerView == null) {
            pickerView = AreaPickerView(this, bean)
            pickerView?.setFinishedListener {
                val sb = StringBuilder()
                for ((index, result) in it.withIndex()) {
                    if (index != it.size - 1) {
                        sb.append(result.name + "-")
                    } else {
                        sb.append(result.name)
                    }
                }
                area_choose.text = sb.toString()
                save.isEnabled = edt_name.toString() != "" && edt_phone.text.toString() != "" && edt_street.text.toString() != ""
            }
        }

        showPopup()
    }

    override fun setAddressBean(): AddressAddBean {
        val list = area_choose.text.split("-")
        for ((index, name) in list.withIndex()) {
            if (index == 0) {
                addressAddBean.province = name
            }
            if (index == 1) {
                addressAddBean.city = name
            }
            if (index == 2) {
                addressAddBean.district = name
            }
        }
        addressAddBean.name = edt_name.text.toString()
        addressAddBean.phone = edt_phone.text.toString()
        addressAddBean.place = edt_street.text.toString()


        return addressAddBean
    }

    override fun setDeleteAddressBean(): DeleteAddressBean {
        return deleteBean!!
    }

    override fun addRegionSuccess() {
        ToastUtil.showToast("添加成功")
        finish()
    }

    override fun updateAddressSuccess() {
        if (isOrderConfirm!!) {
            val intent = Intent()
            intent.putExtra("result", addressAddBean.address_id)
            setResult(Activity.RESULT_OK, intent)
        } else {
            ToastUtil.showToast("保存成功")
        }
        finish()
    }

    override fun deleteAddressSuccess() {
        ToastUtil.showToast("删除成功")
        finish()
    }

    override fun showToast(msg: String) {
        ToastUtil.showToast(msg)
    }

    override fun initListener() {
        save.setOnClickListener(this)
        delete.setOnClickListener(this)
        area_choose.setOnClickListener(object : NoDoubleClickListener(){
            override fun onNoDoubleClick(view: View?) {
                mPresenter?.getRegion(2)
            }
        })

        area_choose.setOnTouchListener { v, event ->
            area_choose.requestFocus()
            if (event?.action == MotionEvent.ACTION_UP){
                v?.performClick()
            }
            true
        }
        edt_name.addTextChangedListener(object : MyTextWatcher(){
            override fun afterTextChanged(s: Editable?) {
                save.isEnabled = s.toString() != "" && edt_phone.text.toString() != "" && edt_street.text.toString() != "" && area_choose.text != "点击选择"
            }
        })
        edt_phone.addTextChangedListener(object : MyTextWatcher(){
            override fun afterTextChanged(s: Editable?) {
                save.isEnabled = s.toString() != "" && edt_name.text.toString() != "" && edt_street.text.toString() != "" && area_choose.text != "点击选择"
            }
        })
        edt_street.addTextChangedListener(object : MyTextWatcher(){
            override fun afterTextChanged(s: Editable?) {
                save.isEnabled = s.toString() != "" && edt_name.text.toString() != "" && edt_phone.text.toString() != "" && area_choose.text != "点击选择"
            }
        })
        is_default.setOnClickListener{
            if (addressAddBean.default_set == 2) {
                addressAddBean.default_set = 1
                is_default?.setImageDrawable(ContextCompat.getDrawable(this, R.mipmap.btn_open))
            } else {
                addressAddBean.default_set = 2
                is_default?.setImageDrawable(ContextCompat.getDrawable(this, R.mipmap.btn_close))
            }
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.save -> {
                if (bean == null) {
                    mPresenter?.addRegion()
                } else {
                    mPresenter?.updateAddress()
                }
            }
            R.id.delete -> mPresenter?.deleteAddress()
        }
    }

    private fun showPopup(){
        val lp = window.attributes
        lp.alpha = 0.38f
        window.attributes = lp
        pickerView?.showAtLocation(edit_address, Gravity.BOTTOM, 0, 0)
    }

    override fun isFullScreen(): Boolean {
        //是否沉浸式， 默认非沉浸式
        return false
    }

    public override fun initCustomerStatusManager() {

    }

    override fun setContentViewId(): Int {
        return R.layout.activity_editaddress
    }

    override fun createPresenter() {
        mPresenter = PEditAddressImpl(mContext, this)
    }

    override fun showLoading() {
        showDefaultDialog()
    }

    override fun hideLoading() {
        hideDefaultDialog()
    }

    open class MyTextWatcher : TextWatcher{
        override fun afterTextChanged(s: Editable?) {
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }

    }
}
